package top.xbaoziplus.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import top.xbaoziplus.company.empty.UserInfo;
import top.xbaoziplus.company.service.UserInfoService;
import top.xbaoziplus.company.mapper.UserInfoMapper;
import org.springframework.stereotype.Service;
import top.xbaoziplus.company.utils.EntityUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService {

    private String[] ignoreFields = new String[]{
            "serialVersionUID",
            "job_id",
            "authority",
            "status",
            "password",
            "ac_status",
            "salary"
    };

    @Override
    public HashMap<String, HashMap<String, Object>> compare(UserInfo userInfo) {
        // 获取数据库中的员工信息
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getJobId, userInfo.getJobId());
        UserInfo infoInDb = this.getOne(wrapper);
        // 将新旧数据转换成map集合
        Map<String, Object> userInfoMap = EntityUtils.entityToMap(userInfo);
        Map<String, Object> infoInDbMap = EntityUtils.entityToMap(infoInDb);
        log.info("旧数据为：{}", infoInDbMap);
        log.info("新数据为：{}", userInfoMap);
        // 更新的字段Map
        HashMap<String, HashMap<String, Object>> map = new HashMap<>(infoInDbMap.size());
        userInfoMap.forEach((key, value) -> {
            // 判断字段或字段数据是否合法
            if (Arrays.asList(ignoreFields).contains(key)) {
                log.info("字段{}更新时被忽略", key);
            } else if (ObjectUtils.isNotEmpty(value)) {
                // 获取更新数据的值
                Object dbValue = infoInDbMap.get(key);
                // 判断新旧的值是否有变化
                if (value != dbValue) {
                    HashMap<String, Object> changeMap = new HashMap<>();
                    // 设置旧数据
                    changeMap.put("old", dbValue);
                    // 设置新数据
                    changeMap.put("new", value);
                    // 将数据保存到map中
                    map.put(key, changeMap);
                }
            }
        });
        return map;
    }
}




